package ru.fivestarter.model.authorisation;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ru.fivestarter.entities.leonardo.RolesLeo;
import ru.fivestarter.entities.leonardo.UsersLeo;
import ru.fivestarter.entities.leonardo.UsersRolesLeo;



/**
 * Session Bean implementation class UserAuthentification
 */
@Stateless
@LocalBean
public class UserAuthentification {
	@PersistenceContext
	private EntityManager em;
	private RolesLeo roleOfUser;
	private String roleName="user"; //роль прописана по умолчанию, ее можно добавить в сигнатуру
    /** 
     * Default constructor. 
     */
    public UserAuthentification() {
        // TODO Auto-generated constructor stub
    }
    public Boolean registration(String login, String password){
    	if(em.createNamedQuery("UsersLeo.findUsersLeoForLogin",UsersLeo.class).setParameter("log", login).getResultList().isEmpty()==true){
    		
    		try{
    			roleOfUser=em.createNamedQuery("RolesLeo.findRolesLeoForRole",RolesLeo.class).setParameter("rolesl", roleName).getSingleResult();
    		}
    		catch (Exception e) {
				// TODO: handle exception
    			return false;
			}
    		UsersLeo registrationUser = new UsersLeo();
        	registrationUser.setLogin(login);
        	registrationUser.setPas(password);
        	UsersRolesLeo userRole = new UsersRolesLeo();
        	userRole.setRole(roleOfUser);
        	userRole.setUser(registrationUser);
        	try{
        		em.persist(registrationUser);
        		em.persist(userRole);
        	}
        	catch (Exception e) {
        		return false;
    		}
        	
        	return true;
    	}
    	else{
    		return false;
    	}
    	
    }
   
}
